cmake_minimum_required(VERSION 3.30.5)
project(shadowhook)
enable_language(ASM)

if(${ANDROID_ABI} STREQUAL "arm64-v8a")
    set(ARCH "arm64")
    set(ARCH_LINK_FLAGS "-Wl,-z,max-page-size=16384")
elseif(${ANDROID_ABI} STREQUAL "armeabi-v7a")
    set(ARCH "arm")
    set(ARCH_LINK_FLAGS "")
endif()

set(TARGET "shadowhook")
file(GLOB SRC *.c arch/${ARCH}/*.c arch/${ARCH}/*.S common/*.c third_party/*/*.c)
add_library(${TARGET} SHARED ${SRC})
target_compile_features(${TARGET} PRIVATE c_std_11)
target_compile_options(${TARGET} PRIVATE -Weverything -Werror)
target_include_directories(${TARGET} PRIVATE . include arch/${ARCH} common third_party/xdl third_party/bsd third_party/lss)
target_link_libraries(${TARGET} log)
target_link_options(${TARGET} PRIVATE ${ARCH_LINK_FLAGS})
if(USEASAN)
    target_compile_options(${TARGET} PRIVATE -fsanitize=address -fno-omit-frame-pointer)
    target_link_options(${TARGET} PRIVATE -fsanitize=address)
else()
    target_compile_options(${TARGET} PRIVATE -Os -ffunction-sections -fdata-sections)
    target_link_options(${TARGET} PRIVATE -Os -Wl,--exclude-libs,ALL -Wl,--gc-sections -Wl,--version-script=${CMAKE_CURRENT_SOURCE_DIR}/shadowhook.map.txt)
endif()

set(TARGET "shadowhook_nothing")
add_library(${TARGET} SHARED nothing/sh_nothing.c)
target_compile_options(${TARGET} PRIVATE -Oz -Weverything -Werror -fno-ident -fno-unwind-tables -fno-asynchronous-unwind-tables)
target_link_options(${TARGET} PRIVATE ${ARCH_LINK_FLAGS} -Wl,--strip-all -Wl,--as-needed -Wl,--hash-style=sysv -Wl,--build-id=none -Wl,-nostdlib -nostartfiles -nodefaultlibs)
find_program(LLVM_OBJCOPY_PATH NAMES "llvm-objcopy" PATHS ${ANDROID_NDK}/toolchains/llvm/prebuilt/*/bin NO_DEFAULT_PATH)
if(LLVM_OBJCOPY_PATH)
    add_custom_command(TARGET ${TARGET} POST_BUILD COMMAND ${LLVM_OBJCOPY_PATH} --remove-section=.comment --remove-section=.ARM.attributes $<TARGET_FILE:${TARGET}>)
endif()
